package com.sdry.web.controller.lz;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sdry.model.lz.InventoryDetail;
import com.sdry.model.lz.InventoryOrder;
import com.sdry.model.lz.LossDetail;
import com.sdry.model.lz.LossSpillover;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.OutStockOrder;
import com.sdry.model.lz.Staff;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.LossDetailService;
import com.sdry.service.lz.LossSpilloverService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StaffService;
import com.sdry.utils.Page;
import com.sdry.utils.PushExample;
import com.sdry.utils.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * @ClassName LossSpilloverController
 * @Description 损溢管理
 * @Author lz
 * @Date 2019年3月25日 10:59:24
 * @Version 1.0
 */
@Controller
@RequestMapping("/lossSpillover")
public class LossSpilloverController {
	
	public static final Integer AFFECT_ROW = 0;
	@Resource
	LossSpilloverService lossSpilloverService;
	@Resource
	StaffService staffService; 
	@Resource
	InventoryService inventoryService;
	@Resource
	MaterielService materielService;
	@Resource
	LossDetailService lossDetailService;
	/**
	 * 新增损溢单
	 * @param response
	 * @param lossSpillover
	 */
	@RequestMapping("/addLossSpillover")
	public void addLossSpillover(HttpServletResponse response,HttpSession httpSession, LossSpillover lossSpillover){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		//创建提交人
		
		ZcSysUserEntity user= (ZcSysUserEntity) httpSession.getAttribute("user");
		if(user == null) {
			lossSpillover.setCreater("1");
		}else {
			lossSpillover.setCreater(user.getId().toString());
		}
		
		lossSpillover.setLoss_spillover_order(String.valueOf("SYDH-" + System.currentTimeMillis()));	
		lossSpillover.setCreater_date(sdf.format(new Date()));
		
		//InventoryDetail detail = inventoryService.queryInventoryDetailById(Long.parseLong(lossSpillover.getMaterialName()));
		//lossSpillover.setMaterialName(detail.getMateriel_name());
		
		String approvalId = lossSpillover.getApproval_id().toString();
		//String copyId = lossSpillover.getCopy_id().toString();
		
		String[] approvalIdArray = approvalId.split(",");
		//String[] copyIdArray = copyId.split(",");
		
		StringBuffer approvalName=new StringBuffer();
		//StringBuffer copyName = new StringBuffer();
		
		/*int result = PushExample.testSendPush("有新的损溢单提交，请查看", "损溢单信息", "测试标签", "2");
		
		if(result==1) {
			System.out.println("正常推送");
		}else if(result == 2) {
			System.out.println("设备未上线");
		}else {
			System.out.println("异常失败");
		}*/
		
		//添加审批人信息
		for (String ids : approvalIdArray) {
			long id = Long.parseLong(ids);
			ZcSysUserEntity staff = staffService.queryStaffById(id);
			approvalName.append(staff.getUserName()+",");
		}
		approvalName.deleteCharAt(approvalName.length() - 1);
		lossSpillover.setApproval_name(approvalName.toString());
		
		//添加抄送人信息
		/*for (String ids : copyIdArray) {
			long id = Long.parseLong(ids);
			ZcSysUserEntity staff = staffService.queryStaffById(id);
			copyName.append(staff.getUserName()+",");
		}*/
		//copyName.deleteCharAt(copyName.length() - 1);
		//lossSpillover.setCopy_name(copyName.toString());
		//修改盘点单状态
//		InventoryOrder io = inventoryService.queryInventoryOrderByNumber(lossSpillover.getInventory_order());
//		if(io != null){
//			inventoryService.updateInventoryOrderById(io.getId()+"", "tab", "2");
//		}
		Long affectRow = lossSpilloverService.addLossSpillover(lossSpillover);
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 新增损益单详细
	 * @param response
	 * @param detail
	 */
	@RequestMapping("/addLossDetail")
	public void addInventoryOrderDetail(HttpServletResponse response, LossDetail detail){
		//新增损益单详细
		Long affectRow =lossDetailService.addLossDetail(detail); 
		if(affectRow > 0){
			//修改盘点单详情状态
			LossSpillover lossSpillover = lossDetailService.queryLossById(detail.getLoss_spillover_id());
			InventoryOrder io = inventoryService.queryInventoryOrderByNumber(lossSpillover.getInventory_order());
			Long detailId = inventoryService.queryInventoryDetailByOrderIdAndMid(io.getId(), detail.getMid());
			int i = inventoryService.updateById(detailId+"", "tab", "1", "lz_inventory_detail");
			if(i > 0){
				//如果某个盘点单下所有盘点单详情的状态都是已审批，修改盘点单的状态
				List<InventoryDetail> list = inventoryService.queryInventoryDetailByOrder(lossSpillover.getInventory_order());
				int sum = 0;
				for(InventoryDetail de : list){
					if(de != null){
						if(de.getTab() == 1){
							sum += 1;
						}
					}
				}
				if(sum == list.size()){
					inventoryService.updateById(io.getId()+"", "tab", "2", "lz_inventory_order");
				}
			}
		}
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/upLossDetail")
	public void upInventoryOrderDetail(HttpServletResponse response, LossDetail detail){
		Long affectRow =lossDetailService.updateLossDetail(detail); 
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 	/**
 	 * 根据ID删除该行数据
 	 * @param response
 	 * @param idArr
 	 */
 	@RequestMapping("/deleteLossSpilloverById")
	public void deleteLossSpilloverById(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr){
 		if(idArr.length > 0){
 			for (int i = 0; i < idArr.length; i++) {
 	            Long affectRow = lossSpilloverService.deleteLossSpilloverById(Long.parseLong(idArr[i]));
 	            if (affectRow > AFFECT_ROW) {
 	                try {
						ResponseUtil.write(response, affectRow);
					} catch (Exception e) {
						e.printStackTrace();
					}
 	            } else {
 	                try {
						ResponseUtil.write(response, AFFECT_ROW);
					} catch (Exception e) {
						e.printStackTrace();
					}
 	            }
 	        }
 		}
	}
	
 	/**
 	 * 行内编辑盘点损溢单
 	 * @param response
 	 * @param id 订单ID
 	 * @param fieldName 修改的字段名称
 	 * @param fieldValue 修改的字段的值
 	 */
 	@RequestMapping("/updateLossSpilloverById")
	public void updateLossSpilloverById(HttpServletResponse response, String id, String fieldName, String fieldValue){
		Long affectRow = lossSpilloverService.updateLossSpilloverById(id, fieldName, fieldValue);
		if(affectRow > AFFECT_ROW){
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
 	
	/**
	 * 分页条件查询损溢单
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryLossSpilloverCriteria")
	public void queryLossSpilloverCriteria(HttpServletResponse response, LzQueryCriteria criteria){
		String keyword01 = criteria.getKeyword01();
        //String keyword02 = criteria.getKeyword02();
        if(keyword01 == null){
            keyword01 = "";
        }
       /* if(keyword02 == null){
            keyword02 = "";
        }*/
        criteria.setKeyword01(keyword01);
       // criteria.setKeyword02(keyword02);
        List<LossSpillover> lossSpilloverList = lossSpilloverService.queryLossSpilloverCriteria(criteria);
        int count = lossSpilloverService.countLossSpilloverCriteria(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(lossSpilloverList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * 分页条件查询损溢详情单
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryLossDetail")
	public void queryLoss(HttpServletResponse response, long lossid){
        List<LossDetail> list = lossDetailService.queryLossDetail(lossid);
        int count = lossDetailService.countLossDetail(lossid);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(list);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	/**
	 * 根据供应商ID分页查询物料
	 * @Title:listPageMaterielByCustomerIdAndWarehouseId
	 * @param page 
	 * @param warehouseId 仓库ID
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/listMaterielByCustomerId")
	public void listPageMaterielByCustomerIdAndWarehouseId(Page page,  String cid,  HttpServletResponse response){
		Map<String, Object> map = new HashMap<>();
		map.put("limit", page.getLimit());
		map.put("page", page.getPage());
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(null, jsonConfig);
		int count = 0;
		List<Materiel> list = new ArrayList<Materiel>();
		if (cid != null && !"".equals(cid) ) {
			map.put("cid", Long.parseLong(cid));
			count = materielService.countmaterielcustomerbyid(map);
			list = materielService.querymaterielcustomerbyid(map);
		}
		jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		System.out.println(jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
	

